package admin.controllers;

import helpers.IdUniqueHelper;

import java.io.IOException;
import java.util.ArrayList;
import java.util.TreeMap;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import admin.data.GeoData;
import admin.forms.GeoForm;

import debugs.GeoDebug;

import models.GeoModel;

public class AddGeoServlet extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
		throws IOException, ServletException {
		TreeMap check = new TreeMap();
		GeoData geoData = new GeoData();
		GeoModel geo = new GeoModel();
		geo.setGeoId(IdUniqueHelper.getId());
		
		ArrayList<GeoModel> geos = geoData.getAll();
		
		request.setAttribute("form", "add");
		request.setAttribute("check", check);
		request.setAttribute("geo", geo);
		request.setAttribute("geos", geos);
		try {
			request.getRequestDispatcher("/admin/pages/form_geo.jsp").forward(request, response);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
		throws IOException, ServletException {
		TreeMap check = new TreeMap();
		GeoData geoData = new GeoData();
		GeoModel geo = new GeoModel();
		
		GeoForm geoForm = new GeoForm();
		TreeMap form = (TreeMap) geoForm.checkValid(request, geo);
		geo = (GeoModel) form.get("geo");
		check = (TreeMap) form.get("checkValid");
		
		if (check.size() == 0) {
			geo.setGeoId(IdUniqueHelper.getId());
			geoData.insert(geo);
			geo = new GeoModel();
			geo.setGeoId(IdUniqueHelper.getId());
			request.setAttribute("success", "Bạn đã thêm thành công.");
			
			GeoDebug.debug(geo);
		}
		
		ArrayList<GeoModel> geos = geoData.getAll();
		
		request.setAttribute("form", "add");
		request.setAttribute("check", check);
		request.setAttribute("geo", geo);
		request.setAttribute("geos", geos);
		try {
			request.getRequestDispatcher("/admin/pages/form_geo.jsp").forward(request, response);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
	
}
